﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace _06序列化和反序列化
{
    class Program
    {
        //和 Java 中的类似
        static void Main(string[] args)
        {
            Man man = new Man();
            man.Name = "张三";
            man.Age = 15;
            man.Gender = "男";

            //创建输出流
            using (FileStream fw = new FileStream(@"E:\\ManObj.txt",FileMode.OpenOrCreate,FileAccess.Write))
            {
                //创建序列化对象
                BinaryFormatter bf = new BinaryFormatter();
                //开始序列化
                bf.Serialize(fw, man);//第一个是输出流,第二个是被序列化的对象
            }
            Console.WriteLine("序列化OK");

            //反序列化,先创建输入流
            using (FileStream fr = new FileStream(@"E:\\ManObj.txt",FileMode.Open,FileAccess.Read))
            {
                //创建序列化对象
                BinaryFormatter bf = new BinaryFormatter();
                //开始反序列化
                Man man2 = (Man)bf.Deserialize(fr);

                Console.WriteLine(man2.Name);
                Console.WriteLine(man2.Age);
                Console.WriteLine(man2.Gender);
            }
            Console.WriteLine("反序列化OK");

            Console.ReadKey();
        }
    }

    [Serializable]//标志位表示该类可被序列化
    public class Man
    {
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }


    } 
}
